//
//  LRXPayViewController.m
//  路人侠
//
//  Created by zhangxulong on 4/6/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXPayViewController.h"
#import "LRXPayHeadView.h"
#import "LRXPayOrder.h"
#import <AlipaySDK/AlipaySDK.h>
#import "LRXPaySuccessController.h"
@interface LRXPayViewController ()
@property (nonatomic,assign) CGFloat nowY;
@property (nonatomic,strong) NSMutableArray * payArrays;
@property (nonatomic,assign) CGFloat sumMoney;
@property (nonatomic,weak) UIButton * zhifuBtn;
@property (nonatomic,copy) NSString * payWay;
@end

@implementation LRXPayViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.payArrays = [NSMutableArray array];
    self.payWay = @"2";
    
    //设置导航栏
    [self layoutNaveView];
    //设置地点的位置
    [self setAddrText:self.sendAddrText withBedRoom:self.bedRoomBlockStr];
    //选择支付方式
    [self selectPayWay];
}

// 设置 导航栏 的设置
- (void)layoutNaveView
{
    //1.1 设置标题
    self.navigationItem.title = @"支付订单";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];    
}

/**
 *  设置地点
 *  @param sendAddrText 送达地点
 *  @param buyAddrText  购买地点
 */
- (void)setAddrText:(NSString *)sendAddrText withBedRoom:(NSString *)bedRoomText
{
    LRXPayHeadView * headView = [[LRXPayHeadView alloc]init];
    [headView addAddrcView:sendAddrText withBedRoom:bedRoomText];
    headView.frame = CGRectMake(0, 0, MainScreenW, headView.maxY);
    self.nowY = headView.maxY;
    [self.view addSubview:headView];
}

//支付方式
- (void)selectPayWay
{
    
    CGFloat sumMoney = 0;
    for (LRXThing * thing in self.buyThingArray) {
        sumMoney += [thing.thingMoney floatValue] * [thing.thingCount floatValue];
    }
    
    self.sumMoney = sumMoney;

    UILabel * payRemaind = [[UILabel alloc]init];
    payRemaind.text = @"付款方式:";
    payRemaind.font = [UIFont systemFontOfSize:24 * hScale];
    payRemaind.frame = CGRectMake(33 * wScale, self.nowY + 25 * hScale, 0, 0);
    [payRemaind sizeToFit];
    [self.view addSubview:payRemaind];
    
    UIImageView * zhifuImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"zhifubao"]];
    zhifuImage.frame = CGRectMake(34 * wScale, self.nowY + 126 * hScale, 35 * wScale, 40 * hScale);
    [self.view addSubview:zhifuImage];
    
    UILabel * zhifuWay = [[UILabel alloc]init];
    zhifuWay.text = @"支付宝支付";
    zhifuWay.font = [UIFont systemFontOfSize:28 * hScale];
    zhifuWay.frame = CGRectMake(CGRectGetMaxX(zhifuImage.frame) + 30 * wScale, self.nowY + 114 * hScale, 0, 0);
    [zhifuWay sizeToFit];
    [self.view addSubview:zhifuWay];
    
    
    UILabel * zhifuWayRemaind = [[UILabel alloc]init];
    zhifuWayRemaind.text = @"推荐有支付宝的用户使用";
    zhifuWayRemaind.font = [UIFont systemFontOfSize:20 * hScale];
    zhifuWayRemaind.textColor = [UIColor colorWithRed:154 green:154 blue:154];
    zhifuWayRemaind.frame = CGRectMake(zhifuWay.frame.origin.x, CGRectGetMaxY(zhifuWay.frame) + 12 * hScale, 0, 0);
    [zhifuWayRemaind sizeToFit];
    [self.view addSubview:zhifuWayRemaind];
    
    
    UIButton * zhifuWaySelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    zhifuWaySelectBtn.frame = CGRectMake(534 * wScale, self.nowY + 118 * hScale, 46 * hScale, 46 * hScale);
    [zhifuWaySelectBtn setImage:[UIImage imageNamed:@"payWay"] forState:UIControlStateNormal];
    [zhifuWaySelectBtn setImage:[UIImage imageNamed:@"payWaySelect"] forState:UIControlStateSelected];
    zhifuWaySelectBtn.selected = YES;
    zhifuWaySelectBtn.tag = 0;
    [zhifuWaySelectBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:zhifuWaySelectBtn];
    [self.payArrays addObject:zhifuWaySelectBtn];
    
    
    UIImageView * huoImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"huodaofukuan"]];
    huoImage.frame = CGRectMake(34 * wScale, CGRectGetMaxY(zhifuImage.frame) + 80 * hScale, 35 * wScale, 40 * hScale);
    [self.view addSubview:huoImage];
    
    UILabel * huoWay = [[UILabel alloc]init];
    huoWay.text = @"货到付款";
    huoWay.font = [UIFont systemFontOfSize:28 * hScale];
    huoWay.frame = CGRectMake(CGRectGetMaxX(huoImage.frame) + 30 * wScale, CGRectGetMaxY(zhifuWayRemaind.frame) + 50 * hScale, 0, 0);
    [huoWay sizeToFit];
    [self.view addSubview:huoWay];
    
    
    UILabel * huoWayRemaind = [[UILabel alloc]init];
    huoWayRemaind.text = @"反正就是推荐学生使用";
    huoWayRemaind.font = [UIFont systemFontOfSize:20 * hScale];
    huoWayRemaind.textColor = [UIColor colorWithRed:154 green:154 blue:154];
    huoWayRemaind.frame = CGRectMake(zhifuWay.frame.origin.x, CGRectGetMaxY(huoWay.frame) + 12 * hScale, 0, 0);
    [huoWayRemaind sizeToFit];
    [self.view addSubview:huoWayRemaind];
    
    
    UIButton * huoWaySelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    huoWaySelectBtn.frame = CGRectMake(534 * wScale, CGRectGetMaxY(huoWay.frame), 46 * hScale, 46 * hScale);
    [huoWaySelectBtn setImage:[UIImage imageNamed:@"payWay"] forState:UIControlStateNormal];
    [huoWaySelectBtn setImage:[UIImage imageNamed:@"payWaySelect"] forState:UIControlStateSelected];
    huoWaySelectBtn.tag = 1;
    [huoWaySelectBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:huoWaySelectBtn];
    [self.payArrays addObject:huoWaySelectBtn];
    
    
    
    
    UIButton * zhifuBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    zhifuBtn.frame = CGRectMake(41 * wScale, CGRectGetMaxY(huoWaySelectBtn.frame) + 92 * hScale, MainScreenW - 82 * wScale, 77 * hScale);
    zhifuBtn.backgroundColor = mainColor;
    zhifuBtn.layer.cornerRadius = 10 * hScale;
    zhifuBtn.layer.masksToBounds = YES;
    [zhifuBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [zhifuBtn addTarget:self action:@selector(checkOrder) forControlEvents:UIControlEventTouchUpInside];
    zhifuBtn.titleLabel.font = [UIFont systemFontOfSize:25 * hScale];
    NSString * zhifuBtnTitle = [NSString stringWithFormat:@"确认支付  ¥%.2lf",round(self.sumMoney * 1.1 * 1000 ) / 1000];
    [zhifuBtn setTitle:zhifuBtnTitle forState:UIControlStateNormal];
    
    self.zhifuBtn = zhifuBtn;
    

    [self.view addSubview:zhifuBtn];
}

- (void)btnClick:(UIButton *)btn{
    
    btn.selected = YES;
    for(UIButton * btnp in self.payArrays){
        if(btn.tag != btnp.tag)
        {
            btnp.selected = NO;
        }
    }
    if(btn.tag == 1){
        [self.zhifuBtn setTitle:@"确认发布" forState:UIControlStateNormal];
        self.payWay = @"1";
    }
    else
    {
        NSString * zhifuBtnTitle = [NSString stringWithFormat:@"确认支付  ¥%.2lf",round(self.sumMoney * 1.1 * 1000 ) / 1000];
        [self.zhifuBtn setTitle:zhifuBtnTitle forState:UIControlStateNormal];
        self.payWay = @"2";
    }
    
    
}
//发布按钮点击  求带订单
- (void)checkOrder
{
     NSMutableArray * thingJSON = [NSMutableArray array];
     for (LRXThing * thing in self.buyThingArray) {
         NSDictionary * thingDic = @{
             @"id":[NSNumber numberWithInt:[thing.thingId intValue]],
             @"count":[NSNumber numberWithInt:[thing.thingCount intValue]]
         };
         [thingJSON addObject:thingDic];
     }
    
    //排序 按照 id 排序
    thingJSON = (NSMutableArray *)[(NSArray *)thingJSON sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * obj1, NSDictionary * obj2) {
        NSInteger obID = [obj1[@"id"] integerValue];
        NSInteger obID2 = [obj2[@"id"] integerValue];
        return obID > obID2;
    }];
    
     //将数组转换成字符串
     NSData * data = [NSJSONSerialization dataWithJSONObject:thingJSON options:0 error:NULL];
     NSString * contentStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
     NSDictionary * verifyParam = @{@"goodsArr":contentStr};
    
     AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
     //验证content的合法性
     [manger POST:verifyGoodsUrl parameters:verifyParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
         NSInteger stausCode = [responseObject[@"data"][@"status_code"] integerValue];
         //content时合法的 发布求带
         if (stausCode == 1) {
         //价钱的总价钱
         NSString * thingMoneySum = [NSString stringWithFormat:@"%lf",round(self.sumMoney * 1.1 * 1000 ) / 1000];
         NSString * startTime = [NSString stringWithFormat:@"%@ %@:%@",[LRXGetTime getTimeForm],self.startTimeFieldText,@"00"];
         NSString * endTime = [NSString stringWithFormat:@"%@ %@:%@",[LRXGetTime getTimeForm],self.endTimeFieldText,@"00"];
         
         endTime = [LRXTimeStamp timeToTimeStamp:endTime];
         startTime = [LRXTimeStamp timeToTimeStamp:startTime];
         NSString * isHome = self.bedroomStr.length > 0  ? @"1":@"0";
         if ([isHome isEqualToString:@"0"]) {
             self.bedroomStr = @"";
         }
             
         NSDictionary * paramter = @{
             @"to_pos":@"XXXXXXXXXXXXXXXX",
             @"back_pos":self.sendAddrText,
             @"req_start_time":startTime,
             @"req_end_time":endTime,
             @"content":contentStr,
             @"total_price":thingMoneySum,
             @"is_home_delivery":isHome,
             @"location_detail":self.bedroomStr,
             @"remark":self.mesgViewText,
             @"pay_type":self.payWay
         };
     
        [MBProgressHUD showMessage:@"正在前往支付宝"];
         AFHTTPSessionManager * manger2 = [AFHTTPSessionManager manager];
         [manger2 POST:checkUrl parameters: paramter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [MBProgressHUD hideHUD];
             if ([responseObject[@"data"][@"status_code"] isEqualToString:@"1"]) {
                 self.tradeNO = responseObject[@"data"][@"trade_no"];
                 self.sign = responseObject[@"data"][@"sign"];
                 
//支付宝支付
                 if ([self.payWay isEqualToString:@"2"]) {
                     //数据的转化 进行支付
                     [self formatConvert];
                 }
//货到付款                 
                 else
                 {
                     [self payForResult:@"9000"];
                 }
             }
             else
             {
                 [MBProgressHUD showError:@"发布失败"];
             }
         
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"发布失败"];
         
         }];
     }
     
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [MBProgressHUD showError:@"网络连接失败"];
     }];
}
- (void)formatConvert
{
    
    NSMutableArray * bodyArray = [NSMutableArray array];
    
    for (LRXThing * thing in self.buyThingArray) {
        NSDictionary * thingDic = @{
                                    @"id":[NSNumber numberWithInt:[thing.thingId intValue]],
                                    @"count":[NSNumber numberWithInt:[thing.thingCount intValue]]
                                    };
        
        [bodyArray addObject:thingDic];
    }
    //排序 按照 id 排序
    self.buyThingArray = (NSMutableArray *)[(NSArray *)self.buyThingArray sortedArrayUsingComparator:^NSComparisonResult(LRXThing * obj1, LRXThing * obj2) {
        NSInteger obID = [obj1.thingId integerValue];
        NSInteger obID2 = [obj2.thingId integerValue];
        return obID > obID2;
    }];
    bodyArray = (NSMutableArray *)[(NSArray *)bodyArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * obj1, NSDictionary * obj2) {
        NSInteger obID = [obj1[@"id"] integerValue];
        NSInteger obID2 = [obj2[@"id"] integerValue];
        return obID > obID2;
    }];
    
 
    int thingCount = 0;
    NSString * subjectStr = @"";
    
    CGFloat sumMoney = 0;
    for (LRXThing * thing in self.buyThingArray) {
        sumMoney += [thing.thingMoney floatValue] * [thing.thingCount floatValue];
    }
    
    self.sumMoney = sumMoney;
    
    
    for (int i = 0; i < self.buyThingArray.count; i++) {
        LRXThing * thing = self.buyThingArray[i];
        thingCount += [thing.thingCount intValue];
        if (i < 2) {
            if (i != 0) {
                subjectStr = [subjectStr stringByAppendingString:@","];
            }
            subjectStr = [subjectStr stringByAppendingString:thing.thingName];
        }
    }
    if (self.buyThingArray.count > 2) {
        subjectStr =  [subjectStr stringByAppendingString:@"等"];
    }
    
    
    subjectStr = [subjectStr stringByAppendingString:[NSString stringWithFormat:@"共%d件商品",thingCount]];
    
    
    //将数组转换成字符串
    NSData * bodyData = [NSJSONSerialization dataWithJSONObject:bodyArray options:0 error:NULL];
    NSString * bodyStr = [[NSString alloc]initWithData:bodyData encoding:NSUTF8StringEncoding];
    [self zhifubaoClick:subjectStr withBody:bodyStr];
    
    
}
- (void)zhifubaoClick:(NSString *)subjectStr withBody:(NSString *)bodyStr
{
    LRXPayOrder *order = [[LRXPayOrder alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = self.tradeNO; //订单ID（由商家自行制定）
    order.subject = subjectStr;
    order.body = bodyStr;
    
    
    order.amount = [NSString stringWithFormat:@"%.2f",round(self.sumMoney * 1.1 * 1000) / 1000]; //商品价格
    order.notifyURL =  @"http://120.24.7.51/app/pay/aliPay"; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    
    

   
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"lurenxiaapp";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (self.sign != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",orderSpec, self.sign, @"RSA"];
        NSLog(@"%@",orderString);
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"结果支付reslut = %@",resultDic);
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                [MBProgressHUD showSuccess:@"交易成功"];
            }
            else
            {
                [MBProgressHUD showError:@"交易失败"];
            }
            
            [self payForResult:resultDic[@"resultStatus"]];
            
        }];
    }
    

}


- (void)payForResult:(NSString *)resultStatus
{
    if ([resultStatus isEqualToString:@"9000"]) {
        LRXPaySuccessController * paysuccess = [[LRXPaySuccessController alloc]init];
        paysuccess.sendTextStr = self.sendAddrText;
        paysuccess.sumMoney = self.sumMoney;
        [self.navigationController pushViewController:paysuccess animated:YES];
//        [self presentViewController:paysuccess animated:YES completion:nil];
        
    }
    
//    if ([self.payDelegate respondsToSelector:@selector(payForOrderResult:)]) {
//        [self.payDelegate payForOrderResult:resultStatus];
//    }
}

- (void)popViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
